
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { toast } from "@/components/ui/sonner";

interface Question {
  id: number;
  text: string;
  options: {
    value: string;
    label: string;
  }[];
}

const quizQuestions: Question[] = [
  {
    id: 1,
    text: "How do you typically approach learning new subjects?",
    options: [
      { value: "visual", label: "I prefer visual aids and diagrams" },
      { value: "auditory", label: "I learn best by listening and discussing" },
      { value: "reading", label: "I enjoy reading and taking notes" },
      { value: "hands-on", label: "I like practical, hands-on activities" }
    ]
  },
  {
    id: 2,
    text: "When working on group projects, what role do you usually take?",
    options: [
      { value: "leader", label: "I often take charge and organize the team" },
      { value: "creative", label: "I contribute creative ideas and perspectives" },
      { value: "support", label: "I help keep everyone on track and supported" },
      { value: "technical", label: "I focus on technical details and execution" }
    ]
  },
  {
    id: 3,
    text: "What motivates you most in your studies?",
    options: [
      { value: "curiosity", label: "Personal curiosity and interest in the subject" },
      { value: "achievement", label: "Achieving good grades and recognition" },
      { value: "future", label: "Preparing for my future career" },
      { value: "social", label: "Learning alongside and connecting with peers" }
    ]
  }
];

export function PersonalityQuiz() {
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [answers, setAnswers] = useState<Record<number, string>>({});
  const [currentAnswer, setCurrentAnswer] = useState<string>("");
  const [isComplete, setIsComplete] = useState(false);
  
  const handleNext = () => {
    if (!currentAnswer) {
      toast.error("Please select an answer before continuing");
      return;
    }
    
    const updatedAnswers = { ...answers, [quizQuestions[currentQuestion].id]: currentAnswer };
    setAnswers(updatedAnswers);
    
    if (currentQuestion < quizQuestions.length - 1) {
      setCurrentQuestion(currentQuestion + 1);
      setCurrentAnswer("");
    } else {
      setIsComplete(true);
    }
  };
  
  const restartQuiz = () => {
    setCurrentQuestion(0);
    setAnswers({});
    setCurrentAnswer("");
    setIsComplete(false);
  };
  
  const progress = ((currentQuestion + (isComplete ? 1 : 0)) / quizQuestions.length) * 100;
  
  const getQuizResult = () => {
    // This is a simplified example. In a real app, you would have more sophisticated analysis.
    const answerCounts: Record<string, number> = {};
    Object.values(answers).forEach(value => {
      answerCounts[value] = (answerCounts[value] || 0) + 1;
    });
    
    const learningStyle = Object.entries(answerCounts).sort((a, b) => b[1] - a[1])[0][0];
    
    switch (learningStyle) {
      case "visual":
      case "auditory":
      case "reading":
      case "hands-on":
        return {
          title: "Learning Style",
          result: `You seem to prefer ${learningStyle} learning approaches.`,
          description: "Understanding your learning style can help you choose study methods that work best for you."
        };
      case "leader":
      case "creative":
      case "support":
      case "technical":
        return {
          title: "Team Role",
          result: `You tend to take on a ${learningStyle} role in teams.`,
          description: "Knowing your natural team role can help you collaborate more effectively with others."
        };
      default:
        return {
          title: "Motivation",
          result: "You have a unique mix of motivational factors.",
          description: "Understanding what drives you can help you stay engaged with your learning journey."
        };
    }
  };
  
  return (
    <Card className="w-full max-w-xl mx-auto">
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          {isComplete ? "Your Result" : "Learn About Yourself"}
          <span className="text-sm font-normal text-muted-foreground">
            {!isComplete && `${currentQuestion + 1}/${quizQuestions.length}`}
          </span>
        </CardTitle>
        {!isComplete && (
          <Progress value={progress} className="h-2 mt-2" />
        )}
      </CardHeader>
      
      <CardContent>
        {!isComplete ? (
          <>
            <h3 className="text-lg font-medium mb-4">{quizQuestions[currentQuestion].text}</h3>
            <RadioGroup value={currentAnswer} onValueChange={setCurrentAnswer} className="space-y-3">
              {quizQuestions[currentQuestion].options.map((option) => (
                <div key={option.value} className="flex items-center space-x-2 rounded-md border p-3 cursor-pointer hover:bg-muted">
                  <RadioGroupItem value={option.value} id={option.value} />
                  <Label htmlFor={option.value} className="flex-grow cursor-pointer">{option.label}</Label>
                </div>
              ))}
            </RadioGroup>
          </>
        ) : (
          <div className="space-y-4 py-4">
            {Object.keys(answers).length === quizQuestions.length && (
              <>
                <div className="bg-accent p-4 rounded-lg">
                  <h3 className="font-medium text-lg">{getQuizResult().title}</h3>
                  <p className="text-lg font-semibold my-2">{getQuizResult().result}</p>
                  <p className="text-muted-foreground">{getQuizResult().description}</p>
                </div>
                <p className="text-center text-muted-foreground">
                  This is just a brief insight. Complete more assessments to learn more about yourself!
                </p>
              </>
            )}
          </div>
        )}
      </CardContent>
      
      <CardFooter className="flex justify-between">
        {!isComplete ? (
          <>
            <Button variant="ghost" onClick={() => currentQuestion > 0 && setCurrentQuestion(currentQuestion - 1)} disabled={currentQuestion === 0}>
              Back
            </Button>
            <Button onClick={handleNext}>
              {currentQuestion < quizQuestions.length - 1 ? "Next" : "Complete"}
            </Button>
          </>
        ) : (
          <Button onClick={restartQuiz} className="w-full">
            Take Another Quiz
          </Button>
        )}
      </CardFooter>
    </Card>
  );
}
